<template>
    <div>
        <div class="search-content">
            <el-form :model="searchContent" ref="searchForm" :inline="true" @submit.native.prevent="handleSearch">
                <el-form-item prop="brand_name" label="厂商搜索：">
                    <el-input v-model.lazy.trim="searchContent.brand_name" clearable placeholder="厂商名称" maxlength="60"></el-input>
                </el-form-item>
                <el-form-item prop="brand_show" label="是否展示：">
                    <el-select v-model="searchContent.brand_show" clearable placeholder="请选择">
                        <el-option
                            v-for="item in brandShow"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="brand_position" label="品牌定位：">
                    <el-select v-model="searchContent.brand_position" clearable placeholder="请选择">
                        <el-option
                            v-for="item in brandPosition"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" native-type="submit" >搜索</el-button>
                    <el-button type="primary" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="search-list">	
            <el-table
                :data="filterData"
                style="width: 100%;"
                :header-cell-style="cellStyle"
                :cell-style="cellStyle"
                :default-sort = "{prop: 'brand_sort' , order: 'ascending'}"
                ref="table"
                @expand-change="expandChange"
                :header-cell-class-name="hdCellClassName" 
                :row-style="selectedstyle"
                :height="oHeight"
                @sort-change="sortChange"
            >
                <el-table-column type="expand" #default="{row}" width="60" label="车型">
                    <el-table
                        :data="row.details"
                        :header-cell-style="cellStyle"
                        :cell-style="cellStyle"
                    >
                        <el-table-column label="序号" type="index" width="70"></el-table-column>
                        <el-table-column label="品牌名称" prop="brand_name" min-width="290">
                            <!-- <el-input v-model="row.brand_name" class="power_brand_name cursorPoint"></el-input> -->
                        </el-table-column>
                        <el-table-column label="是否展示" min-width="185" #default="{row}">
                            <el-switch
                                v-model="row.brand_show"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                active-value="1"
                                inactive-value="0"
	    		        		@change="updateBrandList(row)"
                            ></el-switch>
                        </el-table-column>
	    				<el-table-column label="操作" #default="{row}" width="248">
	    					<div class="cursorPoint" style="color: #3a8ee6;" @click="carsDetail(row.brand_id)">车型管理</div>
	    				</el-table-column>
                    </el-table>
                </el-table-column>
                <el-table-column label="排序" #default="{row}" sortable prop="brand_sort" min-width="150">
                    <el-input v-model="row.brand_sort" class="input_box_sort cursorPoint" @blur="updateBrandList(row, 'sort')" @change="handleChange(row)"></el-input>
                </el-table-column>
                <el-table-column label="厂商" prop="brand_name" min-width="200">
                    <!-- <el-input v-model="row.brand_name" class="power_brand_name cursorPoint"></el-input> -->
                </el-table-column>
                <el-table-column label="品牌定位" prop="brand_position" min-width="290" #default="{row}">
                    <el-select v-model="row.brand_position" placeholder="请选择" style="width: 100px" @change="updateBrandList(row)">
                        <el-option
                            v-for="item in brandPosition"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-table-column>
                <el-table-column label="品牌标识" #default="{row}" min-width="200">
                    <el-image class="brand_icon" :src="row.brand_icon" fit="cover" lazy>
                        <div slot="error" class="image-slot">
                           <i class="el-icon-picture-outline"></i>
                        </div>
                    </el-image>
                </el-table-column>
                <!--el-table-column label="热门品牌" #default="{row}">
                    <el-switch
                        v-model="row.is_hot"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        active-value="1"
                        inactive-value="0"
	    				@change="updateBrandList(row)"
                    ></el-switch>
                </el-table-column-->
                <el-table-column label="是否展示" width="280" #default="{row}">
                    <el-switch
                        v-model="row.brand_show"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        active-value="1"
                        inactive-value="0"
	    				@change="updateBrandList(row)"
                    ></el-switch>
                </el-table-column>
                <!-- <el-table-column label="操作" #default="{row}" width="100"></el-table-column> -->
            </el-table>
        </div>
    </div>
</template>
<script>
import { resize } from "@/common/js/height.js";
export default {
    data() {
        return {
            tableData: [],
            oHeight: 600,
            searchContent: {
                is_search: false,
                brand_name: "",
                _brand_name: "",
                brand_show: "",
                _brand_show: "",
                brand_position: "",
                _brand_position: "",
            },
            brandShow: [
                { label: '是', value: "1" },
                { label: '否', value: "0" }
            ],
            brandPosition: [
                { label: '全部', value: "0" },
                { label: '豪华品牌', value: "1" },
                { label: '中高端品牌', value: "2" },
                { label: '中低端品牌', value: "3" },
                // { label: '入门', value: "4" }
            ],
            currBrandIds: [],
            sortBy: "ascending"
        }
    },
    beforeRouteEnter(to, from, next) {
        let arr = [
            'ytcarsBrandStyle',
            'ytcarsParaConfig',
            'ytcarsBrandImage',
            'ytcarsBrandVideo'
        ]
        if(!arr.includes(from.name)) {
            localStorage.setItem('offsetTop', 0);
            localStorage.setItem('currBrandIds', []);
            localStorage.setItem("search_brand_name", "")
            localStorage.setItem("search_brand_show", "1")
            localStorage.setItem("search_brand_position", "")
        }
         //继续执行
        next();
    },
    created() {
        this.getTableData();
		this.$parent.tabLists = [{ label: "厂商品牌", name: "ytcarsBrandModel" }];
    },
    beforeRouteLeave(to, from, next) {
        // 内容高度
        // console.log(document.querySelector(".is-scrolling-none").scrollHeight)
        
        // 离开组件则记录scrollTop值
        const elScroll = document.querySelector(".is-scrolling-left")
        if (elScroll) {console.log(elScroll.scrollTop, 'elScroll.scrollTop')
            localStorage.setItem('offsetTop', elScroll.scrollTop);
        }
        next();
    },
    methods: {
        async getTableData() {
            let datas = {}
            // if(this.searchContent.is_search) {
            //     datas.brand_name = this.searchContent.brand_name;
            // }
            const res = await this.$http.post('/admin/yt_car/index.php?act=yt_car&op=getBrandList', datas)
            if (res.code == 1) {
                let currBrandIds = localStorage.getItem("currBrandIds").split(",") || [];
                let _row = [];

                // 判断是否存在搜索记录
                let search_brand_name = localStorage.getItem("search_brand_name") || ""
                let search_brand_show = localStorage.getItem("search_brand_show") || ""
                let search_brand_position = localStorage.getItem("search_brand_position") || ""
                if(search_brand_name) {
                    this.searchContent.brand_name = search_brand_name;
                    this.searchContent._brand_name = search_brand_name;
                    this.searchContent.is_search = true;
                }
                if(search_brand_show) {
                    this.searchContent.brand_show = search_brand_show;
                    this.searchContent._brand_show = search_brand_show;
                    this.searchContent.is_search = true;
                }
                if(search_brand_position) {
                    this.searchContent.brand_position = search_brand_position;
                    this.searchContent._brand_position = search_brand_position;
                    this.searchContent.is_search = true;
                }

                this.tableData = res.data.map(item => {
                    // 排序必须转为数字，不然会错乱
                    item.brand_sort = parseInt(item.brand_sort)
                    if(currBrandIds.indexOf(item.brand_id) >= 0) {
                        _row.push(item)
                    }
                    return item;
                });
                this.$nextTick(() => {
                    // 展开
                    for(let row of _row) {
                        // 展开之前记录的所有行 toggleRowExpansion 第二个参数为 true 则会触发 expand-change 和 row-style 绑定的方法(row-style 会执行三次(elementui Bug))
                        this.$refs.table.toggleRowExpansion(row, true); 
                    }
                    setTimeout(() => {
                        let scrollTop = localStorage.getItem('offsetTop') || 0;

                        // 不滑动
                        //document.querySelector(".is-scrolling-none").scrollTop = scrollTop;
                        //document.querySelector(".is-scrolling-none").scrollTo(0, scrollTop)

                        // 采用jquery
                        //$('.is-scrolling-none').animate({scrollTop},1000);

                        // 滑动滚动
                        this.scrollTo(document.querySelector(".is-scrolling-left"), 0, scrollTop)

                    }, 500)
                })
            }
        },
        expandChange(row, expandedRows) {
            if(expandedRows.indexOf(row) >= 0) { // 展开
                this.currBrandIds.push(row.brand_id); // 添加
                row.background = true;
            } else {
                this.currBrandIds.splice(this.currBrandIds.indexOf(row.brand_id), 1); // 移除
                row.background = false;
            }
            localStorage.setItem("currBrandIds", this.currBrandIds); // 记录当前展开的 Row
        },
        selectedstyle ({row, rowIndex}) {
		    if (row.background) {
			    return { "background-color": "#F5F7FA" };
		    } else {
                return {"background-color": "#ffffff"};
            }
	    },
        scrollTo(el, y, scrollTop, speed = 1) {
            setTimeout(() => {
                if (!el) return
                el.scrollTo(0, y);
                if(y >= scrollTop) return;
                if(y < scrollTop) {
                    y = y + speed;
                }
                y = y > scrollTop ? scrollTop : y;
                if(y % 10 == 0) {
                    speed += 100;
                }
                this.scrollTo(el, y, scrollTop, speed);
            }, 1)
        },
        cellStyle() {
            return { "text-align": "center" };
        },
        hdCellClassName() {
            return 'hdCellStyle'
        },
		carsDetail(brand_id){
			this.$router.push({ name:'ytcarsBrandStyle', params: { brand_id}})
		},
        handleChange(row) {
            row.isChange = true;
        },
		async updateBrandList(row, act = null) {
			let datas = {
				brand_id: row.brand_id,
				type: 'brand', // 类型(brand为厂商、品牌、车型更新, brandSub为车款更新)
            }
            if(act == "sort") {
                if(!row.isChange) return;
                datas.brand_sort = row.brand_sort;
            } else {
                // datas = {...datas, is_hot:row.is_hot, brand_show:row.brand_show, sale_state: row.sale_state}
                datas.brand_show = row.brand_show;
                datas.brand_position = row.brand_position;
            }
            const res = await this.$http.post('/admin/yt_car/index.php?act=yt_car&op=updateBrandList', datas)
			if(res.code===1){
				this.$message.success(res.msg)
                if(act == "sort") {
                    // 手动排序
                    this.$refs.table.sort('brand_sort', this.sortBy)
                    row.isChange = false
                }
			}else{
				this.$message.error(res.msg)
			}
        },
        sortChange(obj) {
            this.sortBy = obj.order
        },
        handleSearch() {
            this.searchContent.is_search = true;
            this.handleLoading();
            this.localReset();
            setTimeout(() => {
                this.searchContent._brand_name = this.searchContent.brand_name
                this.searchContent._brand_show = this.searchContent.brand_show
                this.searchContent._brand_position = this.searchContent.brand_position
                localStorage.setItem("search_brand_name", this.searchContent.brand_name)
                localStorage.setItem("search_brand_show", this.searchContent.brand_show)
                localStorage.setItem("search_brand_position", this.searchContent.brand_position)
            }, 100)
        },
        handleReset() {
            if(!this.searchContent.is_search) {
                this.$refs.searchForm.resetFields();
                return
            };
            this.handleLoading();
            this.localReset();
            setTimeout(() => {
                this.searchContent.is_search = false;
                this.searchContent.brand_name = ''
                this.searchContent.brand_show = ''
                this.searchContent.brand_position = ''
                this.searchContent._brand_name = ''
                this.searchContent._brand_show = ''
                this.searchContent._brand_position = ''
            }, 100)
        },
        localReset() {
            localStorage.setItem('offsetTop', 0);
            this.currBrandIds = [];
            localStorage.setItem('currBrandIds', []);
            localStorage.setItem("search_brand_name", '')
            localStorage.setItem("search_brand_show", '')
            localStorage.setItem("search_brand_position", '')
        },
        handleLoading() {
            let loading = this.$loading({
			    lock: true,
			    text: 'Loading',
			    spinner: 'el-icon-loading',
			    background: 'rgba(0, 0, 0, 0.7)'
            })
            /**
             * 由于数据是从tabelData数组直接过滤而来，非重新请求，所以这里loading也只需显示下就可以关闭。
             * 但当在执行loading加载期间，computed机制也被触发了，那么loading.close()会在 计算属性执行完成，才会加载。所以在handleReset()时并不会立即关闭loading
             */
            loading.close()
        },
        /*
        重新请求
        handleSearch() {
            this.searchContent.is_search = true;
            this.getTableData();
        },
        handleReset() {
            if(!this.searchContent.is_search) return;
            this.$refs.searchForm.resetFields();
            this.searchContent.is_search = false;
            this.getTableData();
        },*/
    },
    computed: {
        filterData: {
            get() {
                if(this.tableData.length <= 0) return;
                if(
                    this.searchContent._brand_name || 
                    parseInt(this.searchContent._brand_show) >= 0 ||
                    parseInt(this.searchContent._brand_position) > 0
                ) {
                    return this.tableData.filter(item => {
                        let _item = item
                        if (
                            this.searchContent._brand_name && 
                            !item.brand_name.includes(this.searchContent._brand_name) ||
                            parseInt(this.searchContent._brand_show) >= 0 && 
                            item.brand_show != this.searchContent._brand_show ||
                            parseInt(this.searchContent._brand_position) > 0 && 
                            item.brand_position != this.searchContent._brand_position
                        ) {
                            _item = null
                        }
                        if (_item) return _item
                    })
                } else {
                    return this.tableData
                }
            }
        }
    },
	mounted() {
		resize(this)
	}
}
</script>
<style scoped lang="scss">
.search-list {
    >.el-table{
        border: 1px solid #EBEEF5;
        border-bottom: 0;
    }
}
.input_box_sort /deep/input {
    width: 80px;
    text-align: center;
}
.power_brand_name /deep/input {
    width: 130px;
    text-align: center;
}
.brand_icon {
    width: 60px;
    height: 60px;
    background: #F5F7FA;
    display: flex;
    margin: 0 auto;
    align-items: center;
    justify-content: space-around;
}
.el-image /deep/.el-image__error{
    font-size:12px;
}
/deep/.el-table__expanded-cell{
    padding: 16px 15px 18px!important;
    .el-table{
        border: 1px solid #EBEEF5;
        border-bottom: 0;
        .el-table__header th{
            font-weight:bold!important;
        }
    }
}
/deep/.hdCellStyle{
    padding: 3px 0;
}
/deep/.el-table__body-wrapper{
    overflow: auto;
}
</style>